package com.zust513.service.impl;

import com.zust513.config.SecurityConfig;
import com.zust513.dto.UserDTO;
import com.zust513.entity.Region;
import com.zust513.entity.User;
import com.zust513.mapper.IUserMapper;
import com.zust513.mapper.UserMapper;
import com.zust513.service.UserService;
import lombok.RequiredArgsConstructor;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 用户服务实现类
 */
@Service
@Transactional
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private final IUserMapper iUserMapper;

    private final PasswordEncoder passwordEncoder;

    @Override
    public List<UserDTO> getAllAdmins() {
        List<User> admins = userMapper.findAllAdmins();
        List<UserDTO> adminDTOs = new ArrayList<>();

        for (User admin : admins) {
            adminDTOs.add(convertToDTO(admin));
        }

        return adminDTOs;
    }

    @Override
    public UserDTO getUserById(Integer userId) {
        User user = userMapper.findUserById(userId);
        return user != null ? convertToDTO(user) : null;
    }

    @Override
    public UserDTO addAdmin(UserDTO userDTO) {
        // 检查用户名是否已存在
        if (userMapper.findUserByUsername(userDTO.getUsername()) != null) {
            throw new IllegalArgumentException("用户名已存在");
        }

        User user = new User(); // 直接创建新对象而不是转换
        user.setUsername(userDTO.getUsername());
        user.setPhone(userDTO.getPhone());
        user.setEmail(userDTO.getEmail());
        user.setRole("admin"); // 确保角色为admin
        user.setStatus("active");
        user.setCreatedAt(LocalDateTime.now());

        // 使用PasswordEncoder加密密码
        user.setPasswordHash(passwordEncoder.encode(userDTO.getPassword()));

        // 插入用户并检查结果
        int result = userMapper.insertUser(user);
        if (result <= 0) {
            throw new RuntimeException("添加管理员失败，数据库操作未成功");
        }

        // 确认userId已正确回填
        if (user.getUserId() == null) {
            throw new RuntimeException("添加管理员失败，无法获取用户ID");
        }

        // 返回新创建的管理员信息
        return convertToDTO(user);
    }

    @Override
    public boolean updateUser(UserDTO userDTO) {
        User existingUser = userMapper.findUserById(userDTO.getUserId());
        if (existingUser == null) {
            return false;
        }

        User user = convertToEntity(userDTO);

        // 如果有新密码，则加密
        if (userDTO.getPassword() != null && !userDTO.getPassword().isEmpty()) {
            user.setPasswordHash(passwordEncoder.encode(userDTO.getPassword()));
        } else {
            user.setPasswordHash(existingUser.getPasswordHash());
        }

        return userMapper.updateUser(user) > 0;
    }

    @Override
    public boolean deleteUser(Integer userId) {
        return userMapper.deleteUser(userId) > 0;
    }

    /**
     * 登录
     * @param  username 用户名
     * @param  passwordHash 密码
     * @return 登录成功的用户
     */
    @Override
    public User login(String username,String passwordHash) {
        User getUser = iUserMapper.findUserByUsername(username);
        if (getUser == null) {
            return null;
        }
        if (!passwordEncoder.matches(passwordHash, getUser.getPasswordHash())) {
            return null;
        }
        return getUser;
    }

    /**
     * 注册用户
     * @param user 用户信息
     * @return 注册成功的用户
     */
    @Override
    public User register(User user,Integer deliveryArea) {
        List<User> existUsers = iUserMapper.getUsersByUserName(user.getUsername());
        if (!existUsers.isEmpty()) {
            return null;
        }
        int regionId = 0;
        String password = user.getPasswordHash();
        user.setCreatedAt(LocalDateTime.now());
        user.setStatus("active");
        user.setPasswordHash(passwordEncoder.encode(password));
        if (user.getRole().equals("courier") && deliveryArea != null) {
            regionId = deliveryArea;
        }
        iUserMapper.registerUser(user);
        List<User> users = iUserMapper.getUsersByUserName(user.getUsername());
        if (users == null || users.isEmpty()) {
            throw new RuntimeException("注册失败");
        }
        int userId = users.get(0).getUserId();
        iUserMapper.addAccounts(userId);
        if (user.getRole().equals("courier")) {
            iUserMapper.addCourier(userId);
            iUserMapper.addCourierAndRegion(userId, regionId);
        }
        return users.get(0);
    }

    @Override
    public List<Region> getDeliveryAreas() {
        return iUserMapper.getDeliveryAreas();
    }

    /**
     * 将User实体转换为UserDTO
     */
    private UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setUserId(user.getUserId());
        dto.setUsername(user.getUsername());
        // 不设置密码
        dto.setPhone(user.getPhone());
        dto.setEmail(user.getEmail());
        dto.setRole(user.getRole());
        dto.setStatus(user.getStatus());
        dto.setCreatedAt(user.getCreatedAt());
        dto.setLastLogin(user.getLastLogin());
        return dto;
    }

    /**
     * 将UserDTO转换为User实体
     */
    private User convertToEntity(UserDTO dto) {
        User user = new User();
        user.setUserId(dto.getUserId());
        user.setUsername(dto.getUsername());
        // 密码在方法中处理
        user.setPhone(dto.getPhone());
        user.setEmail(dto.getEmail());
        user.setRole(dto.getRole());
        user.setStatus(dto.getStatus());
        user.setCreatedAt(dto.getCreatedAt());
        user.setLastLogin(dto.getLastLogin());
        return user;
    }
}